package com.syuchen.server.udp;

import com.alibaba.fastjson.JSON;
import com.syuchen.common.Invocation;

import java.lang.reflect.Method;
import java.net.DatagramPacket;

public class UdpTask implements Runnable{

    private DatagramPacket datagramPacket;

    UdpTask(DatagramPacket datagramPacket) {
        this.datagramPacket = datagramPacket;
    }

    @Override
    public void run() {
        try {
            byte[] arr = datagramPacket.getData(); // 获取数据
            int len = datagramPacket.getLength(); // 获取有效长度
            Invocation invocation = JSON.parseObject(new String(arr, 0, len), Invocation.class);
            Class<?> classImpl = Class.forName(invocation.getInterfaceName());
            Method method = classImpl.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
            UdpServer.requestUrlTL.set(datagramPacket.getAddress().toString().substring(1) + ":" + datagramPacket.getPort());
            method.invoke(classImpl.newInstance(), invocation.getParameters());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            UdpServer.requestUrlTL.remove();
        }
    }
}
